/*
 * Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.
 * 
 * This file is part of the Mnova scripting toolkit.
 * 
 * Authorized users of MNova Software may use this file freely, but this file is provided AS IS 
 * with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS 
 * FOR A PARTICULAR PURPOSE.
 */

/*jslint plusplus: true, indent: 4*/
/*global Str, FileDialog, File, Settings, Dir, qsTr, FileInfo, Application, MnUi*/

function importPerchMolfile() {
	'use strict';
	var settingsKey = 'PerchMolfile',
		setts = new Settings(settingsKey),
		defaultDirectory = setts.value("DefaultDir", Dir.home()),
		molfilePath = FileDialog.getOpenFileName(qsTr("Molfile (*.mol)"), qsTr("Select a molfile"), defaultDirectory),
		file = new File(molfilePath),
		fileInfo = new FileInfo(molfilePath),
		molfile = '',
		molItemId;

	if (molfilePath.length !== 0 && file.open(File.ReadOnly)) {
		setts.setValue("DefaultDir", fileInfo.path);
		if (Application.mainWindow.activeDocument === undefined || !Application.mainWindow.activeDocument.isValid()) {
			Application.mainWindow.newDocument();
		}
		molfile = Str.perchMolfileLabelsToNumbers(file.readAll());
		molItemId = Application.molecule.importMolfile(molfile);
		if (molItemId === undefined) {
			throw qsTr("Unable to open molfile");
		}
	}
	return 0;
}

if (this.MnUi && MnUi.scripts_common) {
	MnUi.scripts_common.scripts_common_ImportPerchMolfile = importPerchMolfile;
}
